package com.cyf.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * 文件工具类
 * Created by cage on 2017/4/25.
 */
public class FileUtil {

    private static final Logger logger = LoggerFactory.getLogger(FileUtil.class);
    /**
     * 转换文件到字节数组
     *
     * @param filePath 文件路径
     * @return byte[]  字节数组
     */
    public static byte[] convertFile2ByteArray(String filePath) throws IOException {
        File file = new File(filePath);
        if (!file.exists()) {
            throw new FileNotFoundException("文件不存在!");
        }
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            for (int readNum; (readNum = fis.read(buf)) != -1; ) {
                bos.write(buf, 0, readNum);
            }
            return bos.toByteArray();
        } finally {
            if (fis != null) {
                fis.close();
            }
        }
    }

    /**
     * 保存文件
     *
     * @param file     文件
     * @param dirPath  要保存的路径
     * @param fileName 要保存的文件名（不含后缀）
     */
    public static void saveFile(MultipartFile file, String dirPath, String fileName) throws Exception {
        BufferedOutputStream outputStream = null;
        try {
            File dir = new File(dirPath);
            if (!dir.exists()) {
                boolean createResult = dir.mkdirs();
                if (!createResult) {
                    throw new Exception("创建存储目录(" + dirPath + ")失败！");
                }
            }
            String originalFilename = file.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.indexOf("."));
//            fileName = fileName + suffix;
            fileName = fileName + ".jpg";
            File newFile = new File(dir, fileName);
            if (newFile.exists()) {
                boolean delete = newFile.delete();
                if (!delete) {
                    logger.error("删除文件失败！：{}", dir + fileName);
                }
            }
            outputStream = new BufferedOutputStream(new FileOutputStream(newFile));
            outputStream.write(file.getBytes());
            outputStream.flush();
        } finally {
            if (null != outputStream) {
                outputStream.close();
            }
        }
    }
}
